import { getSearchHistory, saveSearchHistory } from '@/utils/localStorage'

// search 组件
export const state = () => ({
  showSearchPanel: false, // 展开搜索面板
  hotSearchList: [], // 热门搜索关键字
  historyList: [], // 历史搜索 (仅仅保存10条最新记录)
  historyLenthMax: 10
})
export const mutations = {
  setShowSearchPanel (state, bool) {
    state.showSearchPanel = bool
  },
  setHotSearchList (state, val) {
    state.hotSearchList = val
  },
  setHistoryList (state, newInput) {
    // 第一个条件判断 为处理 搜索页 点开始 可以加载到 本地的历史搜索记录
    // 第二个条件判断 过滤 空字符串搜索
    // vuex state.historyList 做修改
    // 修改缓存
    const _his = getSearchHistory()
    if (state.historyList.length === 0 && !newInput) {
      state.historyList = _his.slice(0, state.historyLenthMax)
      return
    }
    if (!newInput || !newInput.trim()) { return }
    const has = _his.includes(newInput)
    state.historyList.unshift(newInput)
    if (has) {
      state.historyList = Array.from(new Set(state.historyList))
    }
    saveSearchHistory(newInput)
  }
}
